package com.wmlive.hhvideo.heihei.discovery;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

import com.wmlive.hhvideo.heihei.beans.discovery.LocalVideoBean;
import com.wmlive.hhvideo.utils.KLog;
import com.wmlive.hhvideo.utils.PermissionUtils;
import com.wmlive.hhvideo.utils.SdkUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by lsq on 6/6/2017.
 */

public class DiscoveryUtil {

    /**
     * 转换时间
     *
     * @param time
     * @return
     */
    public static String convertTime(int time) {
        if (time < 0) {
            return "00:00";
        }
        int minute = time / 60;
        int second = time % 60;
        return (minute < 10 ? ("0" + minute) : String.valueOf(minute))
                + ":" +
                (second < 10 ? ("0" + second) : String.valueOf(second));
    }


    /**
     * 给TextView或者Button设置图片
     *
     * @param view
     * @param drawableId
     * @param direction  0:左 1:上 2:右 3:下
     */
    public static <T extends TextView> void setDrawable(T view, int drawableId, int direction, int width, int height) {
        if (drawableId > 0) {
            Drawable drawable;
            drawable = view.getResources().getDrawable(drawableId);
            drawable.setBounds(0, 0, width, height);
            switch (direction) {
                case 0:
                    view.setCompoundDrawables(drawable, null, null, null);
                    break;
                case 1:
                    view.setCompoundDrawables(null, drawable, null, null);
                    break;
                case 2:
                    view.setCompoundDrawables(null, null, drawable, null);
                    break;
                case 3:
                    view.setCompoundDrawables(null, null, null, drawable);
                    break;
            }
        } else {
            view.setCompoundDrawables(null, null, null, null);
        }

    }

    public static void changeTextColor(TextView view, String string, int start, int end, int colorId) {
        SpannableStringBuilder builder = new SpannableStringBuilder(string);
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(colorId);
        builder.setSpan(colorSpan, start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
        view.setText(builder);
    }

    /**
     * 更新媒体文件
     *
     * @param context
     * @param path
     */
    public static void updateMedia(final Context context, final String path) {
        if (!TextUtils.isEmpty(path)) {
            Observable.just(1)
                    .subscribeOn(Schedulers.io())
                    .map(new Function<Integer, Integer>() {
                        @Override
                        public Integer apply(Integer integer) throws Exception {
                            if (SdkUtils.isKITKAT()) {
                                MediaScannerConnection.scanFile(context, new String[]{path}, null,
                                        new MediaScannerConnection.OnScanCompletedListener() {
                                            public void onScanCompleted(String path, Uri uri) {
                                                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                                                mediaScanIntent.setData(uri);
                                                context.sendBroadcast(mediaScanIntent);
                                            }
                                        });
                            } else {
                                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(new File(path))));
                            }
                            return 1;
                        }
                    })
                    .subscribe();
        }
    }


    /**
     * 通知更新本地视频文件
     *
     * @param context
     * @param listener
     */
    public static void updateLocalVideo(final Context context, final OnScanCompleteListener listener) {
        if (SdkUtils.isKITKAT()) {
            if (SdkUtils.isMarshmallow() && !PermissionUtils.hasSDCardRWPermission(context)) {
                return;
            }
            getAllVideos(context)
                    .map(new Function<List<LocalVideoBean>, String[]>() {
                        @Override
                        public String[] apply(List<LocalVideoBean> localVideoBeen) throws Exception {
                            List<String> folderPath = new ArrayList<String>();
                            int i = 0;
                            for (LocalVideoBean video : localVideoBeen) {
                                folderPath.add(i, video.getPath());
                                i++;
                            }
                            KLog.i("发现本地视频的数量：" + i);
                            return folderPath.toArray(new String[i]);
                        }
                    })
                    .subscribe(new Consumer<String[]>() {
                        @Override
                        public void accept(String[] strings) throws Exception {
                            MediaScannerConnection.scanFile(context.getApplicationContext(), strings, null,
                                    new MediaScannerConnection.OnScanCompletedListener() {
                                        @Override
                                        public void onScanCompleted(String path, Uri uri) {
                                            KLog.i("find video path:" + path + "_uri:" + uri);
                                            if (listener != null) {
                                                if (uri == null) {//扫描结束了
                                                    listener.onScanComplete(path, uri);
                                                }
                                            }
                                        }
                                    });
                        }
                    });

        } else {
            updateLocalMedia4_4(context);
        }
    }

    public interface OnScanCompleteListener {
        void onScanComplete(String path, Uri uri);
    }

    /**
     * 4.4以下通知媒体更新
     *
     * @param context
     */
    private static void updateLocalMedia4_4(Context context) {
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
                + Environment.getExternalStorageDirectory())));
    }


    /**
     * 获取本地视频
     *
     * @param context
     * @return
     */
    public static Observable<List<LocalVideoBean>> getAllVideos(final Context context) {
        return Observable.just(1)
                .delay(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .map(new Function<Integer, List<LocalVideoBean>>() {
                    @Override
                    public List<LocalVideoBean> apply(Integer integer) throws Exception {
                        long start = System.currentTimeMillis();
                        KLog.i("====开始查询：" + start);
                        Cursor cursor = queryVideo(context, null, null, null);
                        KLog.i("====结束查询,耗时：" + (System.currentTimeMillis() - start));
                        start = System.currentTimeMillis();
                        KLog.i("====开始组装：" + start);
                        List<LocalVideoBean> arrayList = new ArrayList<>();
                        LocalVideoBean bean;
                        if ((cursor != null) && (cursor.moveToFirst()))
                            do {
                                bean = new LocalVideoBean(
                                        cursor.getLong(0),
                                        cursor.getString(1),
                                        cursor.getString(2),
                                        cursor.getString(3),
                                        cursor.getString(4),
                                        cursor.getString(5),
                                        cursor.getInt(6),
                                        cursor.getInt(7),
                                        cursor.getString(8));
                                arrayList.add(bean);
                            } while (cursor.moveToNext());
                        if (cursor != null) {
                            cursor.close();
                        }
                        KLog.i("====结束组装，耗时：" + (System.currentTimeMillis() - start));
                        return arrayList;
                    }
                });
    }

    /**
     * 查询Video
     *
     * @param context
     * @param selection
     * @param paramArrayOfString
     * @param sortOrder
     * @return
     */
    private static Cursor queryVideo(Context context, String selection, String[] paramArrayOfString, String sortOrder) {
        return context.getContentResolver().query(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
                new String[]{
                        MediaStore.Video.Media._ID,
                        MediaStore.Video.Media.TITLE,
                        MediaStore.Video.Media.ALBUM,
                        MediaStore.Video.Media.ARTIST,
                        MediaStore.Video.Media.DISPLAY_NAME,
                        MediaStore.Video.Media.MIME_TYPE,
                        MediaStore.Video.Media.DURATION,
                        MediaStore.Video.Media.SIZE,
                        MediaStore.Video.Media.DATA},
                selection, paramArrayOfString, sortOrder);

    }


}
